package com.adminx.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;

import com.adminx.service.MyUserDetailsService;

public class MySourceDecisionManager implements FilterInvocationSecurityMetadataSource{
	
	private static final Logger LOGGER = Logger.getLogger(MySourceDecisionManager.class);
	
	private UrlMatcher urlMatcher = new AntUrlPathMatcher();
	
	private MyUserDetailsService userDetailsService;
	
	//优先注入MyUserDetailsService，并加载权限资源映射关系
	public MySourceDecisionManager(MyUserDetailsService userDetailsService){
		this.userDetailsService = userDetailsService;
		loadResourceDefine();
	}
	public MyUserDetailsService getUserDetailsService() {
		return userDetailsService;
	}
	public void setUserDetailsService(MyUserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	/**
	 *加载权限与资源的映射关系
	 */
	private void loadResourceDefine(){
		Map<String, Collection<ConfigAttribute>> resourceMap = null;

		LOGGER.info("【安全框架】资源初始化！");
		if(resourceMap == null){
			LOGGER.info("【安全框架】注入MyUserDetailsService！");
			resourceMap = userDetailsService.loadResourcesAndAuthority();
			MyAuthResoMapping.setResourceMap(resourceMap);
		}
	}
	
	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {
		
		//获取权限资源数据
		Map<String, Collection<ConfigAttribute>> resourceMap = MyAuthResoMapping.getResourceMap();
		//获取用户请求url
		String url = ((FilterInvocation)obj).getRequestUrl();
		
		if(url != null){
			//匹配url
			if(resourceMap.get(url) != null){
				return resourceMap.get(url);
			}
		}
		
		//若资源带参数，则去掉
		if(url.contains("?")){
			String[] str = url.split("\\?");
			url = str[0];
		}
		
		Iterator<String> it = resourceMap.keySet().iterator();
		while(it.hasNext()){
			if(urlMatcher.pathMatchesUrl(url, it.next())){
				return resourceMap.get(it.next());
			}
		}
		
		Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
		ConfigAttribute configAttribute = new SecurityConfig("NONE");
		configAttributes.add(configAttribute);
		return configAttributes;
	}
	
	/**
	 * 必须返回true，否则报错
	 */
	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}
}
